package pub.tbc.mybatis.webconfig;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import pub.tbc.mybatis.assist.plugin.TimeInterceptor;
import pub.tbc.mybatis.assist.plugin.page.MySqlPagePlugin;

import javax.sql.DataSource;

/**
 * @author tbc on 2017/5/17 17:02:39.
 */
@Slf4j
@Configuration
public class MyBatisConfig {

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        log.debug("##########################3## => sqlSessionTemplate");
        return new SqlSessionTemplate(sqlSessionFactoryBean.getObject());
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        log.debug("##########################3## => sqlSessionFactoryBean");
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("pub.tbc.mybatis");

        sqlSessionFactoryBean.setPlugins(new Interceptor[]{timeInterceptor(), pagePlugin()});

        return sqlSessionFactoryBean;
    }

//    public SqlSessionFactory sqlSessionFactory(SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
//        return sqlSessionFactoryBean.getObject();
//    }
//
//    private void configPlugin(org.apache.ibatis.session.Configuration configuration) {
//        log.debug("##########################3## ==> configPlugin: {}", configuration);
//        configuration.addInterceptor(timeInterceptor());
//        configuration.addInterceptor(pagePlugin());
//    }


    @Bean
    public Interceptor pagePlugin() {
        return new MySqlPagePlugin();
    }

    @Bean
    public Interceptor timeInterceptor() {
        return new TimeInterceptor();
    }

}
